//
//  Status.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/13.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
import SDWebImage
class Status: NSObject {

    var created_at: String?
    
    var id: Int = 0
    
    var text: String?
    //来源
    var source: String? {
        didSet {
            source = source?.hrefLink().text
        }
    }
    //配图数组
    var pic_urls: [[String:AnyObject]]? {
        didSet{
 
        if pic_urls!.count == 0 {
            return
        }
//            实例化数组
            strodPictureURLs = [NSURL]()
            strodLargePictureURLs = [NSURL]()
            
            //遍历字典声称url的数组
            for dict in pic_urls! {
                if let urlstring = dict["thumbnail_pic"] as? String{
                    strodPictureURLs?.append(NSURL(string: urlstring)!)
                    
                    //大图的数组
                    let largeURLString = urlstring.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    strodLargePictureURLs?.append(NSURL(string:largeURLString)!)
                    
                }
            }
        }
    
    }
    //保存配图的URL的数组
   private var strodPictureURLs:[NSURL]!
    //保存大图的URL数组
    private var strodLargePictureURLs:[NSURL]!
    
//    配图的url的数组,如果原创微博，返回 strodPictureURLs，
//    如果是转发微博，返回retweeted_status.strodPictureURLs
    var picTureURLs: [NSURL]? {
        return retweeted_status == nil ? strodPictureURLs :retweeted_status?.strodPictureURLs
    }
    //返回大图的url数组
    var largePictrueURL: [NSURL]? {
        return retweeted_status == nil ? strodLargePictureURLs : retweeted_status?.strodLargePictureURLs
    }
    
//    转发微博
    var retweeted_status: Status?
    
//    显示微博所需的行高
    var rowHeight: CGFloat?

    //用户记录
    var user:User?
    
    //加载微博数据
    class func loadStatus(sinct_id:Int,max_id:Int,finished:(datalist: [Status]?,error: NSError?)->()) {
        
        NetWorkingTools.sharedTools.loadStatus(sinct_id,max_id:max_id) { (result, error) -> () in
            
            if error != nil{
                finished(datalist: nil, error: error);
                return
            }
            
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                //遍历数组 字典转模型
                var list = [Status]()
                
                for dict in array {
                    
                list.append(Status(dict: dict))
                    
                }
                //图片缓存
                self.cachaWebImage(list,finished:finished)
                
            } else {
                finished(datalist: nil, error: nil)
            }
        }
    }
    //缓存微博图片 缓存结束后 才刷新数据
    private class func cachaWebImage(list:[Status],finished:(datalist: [Status]?,error: NSError?)->()) {
        //图片缓存大小
        var dataLenth = 0
        
        //创建一个调度组
       let group = dispatch_group_create()
        
        //循环便利数组
        for Status in list {
            guard let urls = Status.picTureURLs else {
                
                continue
            }

            for imageurl in urls {
//                入组
            dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(imageurl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) in
                    
                    //如果下载图像失败，image转换到二进制数据的时候会崩溃
                    if image != nil {
                        let data = UIImagePNGRepresentation(image)!
                        dataLenth += data.length
                    }

//                    出组
                    dispatch_group_leave(group)
                })
            }
        }
        //监听所有缓存的通知
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("over \(dataLenth / 1024) k")
            //获得完整的微博数组，可以回调
            finished(datalist: list, error: nil)
        }
    }
    
    //构造函数
    init(dict: [String: AnyObject]){
        super.init()
        //会调用 setvalue forkey，给每一个属性赋值
   setValuesForKeysWithDictionary(dict)
}
    override func setValue(value: AnyObject?, forKey key: String) {
        //如果属性是urse，单独处理
        if key == "user" {
            
            //判断 value是否是一个有效值
            if let dict = value as? [String:AnyObject]{
                //这里是创建用户数据
                user = User(dict:dict)
            }
      
            return
        }
//        转发微博
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = Status(dict: dict)
            }
            return
        }
        
        super.setValue(value, forKey: key)
}
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        
        let keys = ["created_at", "id", "text", "source", "pic_urls"]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    }
}

